package com.yzf.config;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.yzf.service.*;
import com.yzf.util.ApiContext;
import com.yzf.util.RedisTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

@Service
public class MyUserDetailsService implements UserDetailsService {

	Logger logger = LoggerFactory.getLogger(MyUserDetailsService.class);

	@Autowired
	private IUserService userService;

	@Autowired
	private ApiContext apiContext;

	/**
	 * 授权的时候是对角色授权，而认证的时候应该基于资源，而不是角色，因为资源是不变的，而用户的角色是会变的
	 */
	@Override
	public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
//		apiContext.setCurrentProviderId(1L);
		QueryWrapper<com.yzf.entity.User> queryWrapper=new QueryWrapper<>();
		com.yzf.entity.User user = userService.getOne(queryWrapper.eq("user_name", account));
		apiContext.setCurrentProviderId(user.getComponyId().longValue());
		logger.info("{},尝试登录---{}", account, user);

		if (null == user) {
			throw new UsernameNotFoundException("没有此用户：" + account);
		}
		// 用来存放用户拥有的权限集合
		List<SimpleGrantedAuthority> authorities = new ArrayList<>();

		return new User(user.getUserName(), user.getPassword(), authorities);
	}
}